package hk.ust.comp3111.ustnutrition;

import hk.ust.comp3111.ustnutrition.data.DataAccessor;
import hk.ust.comp3111.ustnutrition.data.db.Food;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.util.AttributeSet;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.TextView;

public class EatNowCardView extends LinearLayout
{
	public EatNowCardView(Context context)
	{
		super(context);
	}

	public EatNowCardView(Context context, AttributeSet attrs)
	{
		super(context, attrs);
	}

	@SuppressLint("NewApi")
	public EatNowCardView(Context context, AttributeSet attrs, int defStyle)
	{
		super(context, attrs, defStyle);
	}

	public void setFood(Food food)
	{
		if (mTask != null)
		{
			mTask.cancel(true);
			mTask = null;
		}

		ViewHolder vh = (ViewHolder)getTag();
		vh.foodView.setText(food.getName());
		vh.restaurantView.setText(food.getRestaurantStr());
		vh.photoView.setImageDrawable(null);
		showFoodImage(food);
	}

	@Override
	protected void onFinishInflate()
	{
		super.onFinishInflate();
		ViewHolder vh = new ViewHolder() {};
		vh.photoView = (ImageView)findViewById(R.id.photo);
		vh.foodView = (TextView)findViewById(R.id.food);
		vh.restaurantView = (TextView)findViewById(R.id.restaurant);
		setTag(vh);
	}

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
	{
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);

		ViewHolder vh = (ViewHolder)getTag();
		ViewGroup.LayoutParams params = vh.photoView.getLayoutParams();
		params.height = (int)(vh.photoView.getMeasuredWidth() / 16.0 * 9.0);
		vh.photoView.setLayoutParams(params);
	}

	private static class ViewHolder
	{
		public ImageView photoView;
		public TextView foodView;
		public TextView restaurantView;
	}

	private void showFoodImage(Food food)
	{
		if (food.getPhoto() == null)
		{
			return;
		}

		ViewHolder vh = (ViewHolder)getTag();
		final ImageView v = vh.photoView;
		mTask = new DownloadImageTask(v.getMeasuredWidth(), 0)
				{
					@Override
					protected void onPostExecute(Bitmap result)
					{
						if (result != null)
						{
							v.setImageBitmap(result);
							v.setScaleType(ScaleType.CENTER_CROP);
						}
						else
						{
							v.setImageResource(android.R.drawable.ic_menu_gallery);
							v.setScaleType(ScaleType.CENTER);
						}
					}
				};
		mTask.execute(DataAccessor.Instance.getResource(food.getPhoto()));
	}

	private DownloadImageTask mTask;
}
